package com.example.cofeed.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.cofeed.R;
import com.example.cofeed.adapter.HomeAdapter;
import com.example.cofeed.adapter.SearchAdapter;
import com.example.cofeed.adapter.SearchHotAdapter;
import com.example.cofeed.adapter.SearchRecommendAdapter;
import com.example.cofeed.api.ApiService;
import com.example.cofeed.base.BaseActivity;
import com.example.cofeed.callback.DialogCallback;
import com.example.cofeed.callback.LzyResponse;
import com.example.cofeed.constant.IntentKeyConstant;
import com.example.cofeed.constant.SputilsConstant;
import com.example.cofeed.entity.Article;
import com.example.cofeed.entity.Suoyin;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by mqwang on 2017/12/6.
 */

public class SearchActivity extends BaseActivity implements OnRefreshLoadMoreListener {
    @BindView(R.id.search_et)
    EditText searchEt;
    @BindView(R.id.search_tv)
    TextView searchTv;
    @BindView(R.id.rv_list)
    RecyclerView mRvList;
    @BindView(R.id.rv_hot)
    RecyclerView mRvHot;
    @BindView(R.id.rv_recommend)
    RecyclerView mRvRecommend;
    @BindView(R.id.layout_empty)
    LinearLayout mLayoutEmpty;
    @BindView(R.id.layout_hot)
    LinearLayout mLayoutHot;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;
    private SearchAdapter granaryAdapter;
    private String searchKey;
    private int page = 1;
    private SearchHotAdapter mSearchHotAdapter;
    private SearchRecommendAdapter mSearchRecommendAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_search;
    }


    @Override
    protected boolean isNeedTitleBar() {
        return false;
    }

    @Override
    protected void init(Bundle savedInstanceState, View container) {

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mRvList.setLayoutManager(linearLayoutManager);
        granaryAdapter = new SearchAdapter();
        mRvList.setAdapter(granaryAdapter);

        granaryAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (ObjectUtils.isEmpty(SPUtils.getInstance().getString(SputilsConstant.TOKEN))) {
                    ActivityUtils.startActivity(LoginActivity.class);
                    return;
                }
                Article article = (Article) adapter.getData().get(position);
                Intent intent = new Intent(mContext, WebViewActivity.class);
                intent.putExtra(IntentKeyConstant.ID, article.infoid);
                intent.putExtra(IntentKeyConstant.URL, article.urlpath);
                startActivity(intent);

            }
        });

        searchEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    searchKey = searchEt.getText().toString().trim();
                    if (TextUtils.isEmpty(searchKey)) {
                        showToast("请输入搜索关键字");
                        return false;
                    }

                    onRefresh(mRefreshLayout);
                    KeyboardUtils.hideSoftInput(SearchActivity.this);

                }
                return false;
            }
        });

//        searchEt.setOnFocusChangeListener((view, b) -> {
//            if (searchEt.isFocused()) {
//                if (b) {
////                    adapter.clearData();
//                    if (mRefreshLayout.getVisibility() == View.VISIBLE) {
//                        mRefreshLayout.setVisibility(View.GONE);
//                    }
//                    if (mRvRecommend.getVisibility() == View.VISIBLE) {
//                        mRvRecommend.setVisibility(View.GONE);
//                    }
//                    if (mLayoutHot.getVisibility() == View.GONE) {
//                        mLayoutHot.setVisibility(View.VISIBLE);
//                    }
//
//                }
//            }
//        });

        searchEt.setOnTouchListener((view, motionEvent) -> {
            searchEt.setFocusable(true);
            searchEt.setFocusableInTouchMode(true);
            searchEt.requestFocus();
            return false;
        });

        mRvRecommend.setLayoutManager(new LinearLayoutManager(this));
        mSearchRecommendAdapter = new SearchRecommendAdapter();
        mRvRecommend.setAdapter(mSearchRecommendAdapter);
        mSearchRecommendAdapter.setOnItemClickListener((adapter, view, position) -> {
            Suoyin s = (Suoyin) adapter.getData().get(position);
            searchEt.setText(s.title);
            searchKey = s.title ;
            onRefresh(mRefreshLayout);

        });

        searchEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (ObjectUtils.isNotEmpty(s)){
//                    mSearchRecommendAdapter.getData().clear();
                    setGone(1);
                    getRecWord(s.toString());
                }else {
                    setGone(0);
                }

            }
        });

        getHotData();
        setGone(0);
        mRefreshLayout.setOnRefreshLoadMoreListener(this);
    }

    private void setGone(int type){
        switch (type){
            case 0:
                if (mRefreshLayout.getVisibility() == View.VISIBLE) {
                    mRefreshLayout.setVisibility(View.GONE);
                }
                if (mRvRecommend.getVisibility() == View.VISIBLE) {
                    mRvRecommend.setVisibility(View.GONE);
                }
                if (mLayoutHot.getVisibility() == View.GONE) {
                    mLayoutHot.setVisibility(View.VISIBLE);
                }
                break;
                //索引
            case 1:
                if (mRefreshLayout.getVisibility() == View.VISIBLE) {
                    mRefreshLayout.setVisibility(View.GONE);
                }
                if (mRvRecommend.getVisibility() == View.GONE) {
                    mRvRecommend.setVisibility(View.VISIBLE);
                }
                if (mLayoutHot.getVisibility() == View.VISIBLE) {
                    mLayoutHot.setVisibility(View.GONE);
                }
                break;
                //搜索结果
            case 2:
                if (mRefreshLayout.getVisibility() == View.GONE) {
                    mRefreshLayout.setVisibility(View.VISIBLE);
                }
                if (mRvRecommend.getVisibility() == View.VISIBLE) {
                    mRvRecommend.setVisibility(View.GONE);
                }
                if (mLayoutHot.getVisibility() == View.VISIBLE) {
                    mLayoutHot.setVisibility(View.GONE);
                }
                break;
        }

    }

    /**
     * 获取索引
     * @param s
     */
    private void getRecWord(String s){
        ApiService.search_get_words(this, s, new DialogCallback<LzyResponse<List<Suoyin>>>() {
            @Override
            public void onSuccess(Response<LzyResponse<List<Suoyin>>> response) {
                mSearchRecommendAdapter.setNewData(response.body().data);
            }
        });
    }

    /**
     * 获取热门
     */
    private void getHotData(){
        mRvHot.setLayoutManager(new LinearLayoutManager(this));
        mSearchHotAdapter = new SearchHotAdapter();
        mRvHot.setAdapter(mSearchHotAdapter);
        mSearchHotAdapter.setOnItemClickListener((adapter, view, position) -> {
            Suoyin s = (Suoyin) adapter.getData().get(position);
            searchEt.setText(s.title);
            searchKey = s.title ;

            onRefresh(mRefreshLayout);

        });

        ApiService.search_hotwords(this, new DialogCallback<LzyResponse<List<Suoyin>>>() {
            @Override
            public void onSuccess(Response<LzyResponse<List<Suoyin>>> response) {
                mSearchHotAdapter.setNewData(response.body().data);
            }
        });

    }

    private List<Article> mList = new ArrayList<>();

    private void autoRefresh() {
        setGone(2);

        KeyboardUtils.hideSoftInput(this);
        ApiService.search_v2(this, searchKey, page, new DialogCallback<LzyResponse<List<Article>>>() {
            @Override
            public void onSuccess(Response<LzyResponse<List<Article>>> response) {
                if (ObjectUtils.isNotEmpty(response.body().data)) {
                    page++;
                    mList.addAll(response.body().data);
                }
                granaryAdapter.setNewData(mList);

                if (ObjectUtils.isEmpty(mList)) {
                    mLayoutEmpty.setVisibility(View.VISIBLE);
                }else {
                    mLayoutEmpty.setVisibility(View.GONE);
                }

                finishRefresh(mRefreshLayout);
            }

            @Override
            public void onError(Response<LzyResponse<List<Article>>> response) {
                super.onError(response);
                finishRefresh(mRefreshLayout);
            }
        });


    }

    @OnClick({R.id.iv_back, R.id.search_tv})
    public void onViewClicked(View view) {
        KeyboardUtils.hideSoftInput(SearchActivity.this);
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.search_tv:
                finish();
//                String s = searchEt.getText().toString();
//                if (TextUtils.isEmpty(s)){
//                    showToast("请输入关键字");
//                    return ;
//                }
                break;
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        autoRefresh();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        page = 1;
        mList.clear();
        autoRefresh();
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
}
